var 
    router = require('express').Router(),
    uuid = require('uuid'),
    _ = require('underscore'),
    db = require('../db'),
    MonitorModel = db.get('Monitor'),
    LogModel = db.get('Log'),
    logger = require('log4js').getLogger(),
    mon = require('../monitor');



router.post('/monitor', function (req, res){
    var _d = req.body;
    var _m = {
        url: _d.url,
        title: _d.title,
        id: uuid.v1(),
        onwer: _d.onwer,
        tags: (_d.tags || '').split(','),
        status: 0,
        availd: _d.availd || 100,
        autoStart: _d.autoStart || false,
        interval: parseInt( _d.interval || 3000 )
    };
    var monitor = new MonitorModel(_m);

    _m.detector = {
        runner: require('../monitor/detector/http'),
        callback: function(data){
            var log = new LogModel({
                log: data,
                mid: monitor.id,
                url: _d.url
            });
            log.save(function(error){
                if(!!error){
                    logger.error(error);
                }

            });
            // logger.info(data);
        },
        data:{
            timeout: 10000,
            url: _d.url
        }
    };

    monitor.save(function (error){
        if(!!error){
            res.send(db.handlerError(error));
        }else{
            var m = mon.create(monitor.id, _m);
            res.send({
                code: 200,
                result:{
                    id: monitor.id
                }
            });
        }
    });  
});


router.post('/monitor/:action/:mid', function (req, res){
    var mid = req.params.mid;
    var action = req.params.action;
    if(!action){
        res.send({
            code: 400,
            msg: 'Must be set an action, eg stop'
        });
    }else{
        var ro = { code: 200};
        switch (action) {
            case 'start': 
                if(!mon.start(mid)){
                    ro.code = 500;
                }            
                break;
            case 'stop':
                if(!mon.stop(mid)){
                    ro.code = 500;
                }
                break;
            default:
                ro.code = 500;
                ro.msg = 'No such action';
        }
        res.send(ro);           
    }
});



router.get('/monitor/:mid', function (req, res){
    var mid = req.params.mid;
    res.send(mon.status(mid));
});



module.exports = router;
